'use strict'

import {app, BrowserWindow, globalShortcut, Notification, Menu, Tray, ipcMain, crashReporter} from 'electron'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */

if (process.env.NODE_ENV !== 'development') {
    global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
let mainWindow;
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
    app.quit();
} else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
        // 当运行第二个实例时,将会聚焦到myWindow这个窗口
        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore();
            mainWindow.focus()
        }
    });
}
const winURL = process.env.NODE_ENV === 'development'
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`;

try {
    const unhandled = require('electron-unhandled');

    unhandled();
} catch (e) {
    console.log(e)
}

const {execFile} = require('child_process');
const path = require('path');
const dir = process.env.NODE_ENV === 'production' ? '../../../../dongle_service.exe' : '../renderer/dongle/dongle_service.exe';
const reportDir = process.env.NODE_ENV === 'production' ? '../../../../report/' : '../report/';
const connectdIco = path.join(__dirname, process.env.NODE_ENV === 'production' ? '../../../../100.png' : '../../static/100.png');
const unconnectdIco = path.join(__dirname, process.env.NODE_ENV === 'production' ? '../../../../100GRAY.png' : '../../static/100GRAY.png');
let DONGLE_SERVICE = path.join(__dirname, dir);
let dongleResetMode = 1;
let ls, lsDelay = 0;
let tray = null;

const initDongle = () => {
    return execFile(DONGLE_SERVICE, [''], {maxBuffer: 100000000000 * 100000000000, timeout: 0}, (a, b, c) => {
        if (dongleResetMode === 1) {
            tray.setImage(unconnectdIco);
            ls = initDongle();
        }
        dongleResetMode = 1;
    });
};


process.argv.forEach((value) => {
    if (value.indexOf('-donotshow') !== -1) lsDelay = 60000;
});

const kill = require('tree-kill');
let killDongle = () => {
    if (ls) {
        dongleResetMode = 2;
        kill(ls.pid)
    }
};

function createWindow() {
    /**
     * Initial window options
     */

    setTimeout(() => {
        ls = initDongle();
    }, lsDelay / 20);
    app.setPath('temp', 'd:/report');

    crashReporter.start({
        companyName: '123',
        submitURL: '',
        uploadToServer: false,
    });
    mainWindow = new BrowserWindow({
        useContentSize: true,
        show: false,
        closable: true,
        frame: false,
        height: 600,
        width: 920,
        resizable: false,
        transparent: true,
        webPreferences: {nodeIntegration: true}
    });

    mainWindow.webContents.on('crashed', () => {
        recordCrash().then(() => {
            if (index === 0) reloadWindow(mainWindow);
        }).catch((e) => {
            console.log('err', e);
        });
    });

    function recordCrash() {
        return new Promise(resolve => {
            // 崩溃日志请求成功....
            resolve();
        })
    }

    function reloadWindow(mainWin) {
        if (mainWin.isDestroyed()) {
            app.relaunch();
            app.exit(0);
        } else {
            BrowserWindow.getAllWindows().forEach((w) => {
                if (w.id !== mainWin.id) w.destroy();
            });
            mainWin.reload();
        }
    }


    /** 注册图标 **/
    tray = new Tray(unconnectdIco);

    const contextMenu = Menu.buildFromTemplate([
        {
            label: '重启设备', click: () => {
                killDongle();
            }
        },
        {
            label: '断开设备链接', click: () => {
                mainWindow.webContents.send('setOffDevice')
            }
        },
        {
            label: '重新连接所有设备', click: () => {
                mainWindow.webContents.send('setOnDevice')
            }
        },
        {
            label: '获取离线数据', click: () => {
                mainWindow.webContents.send('getOfflineData')
            }
        },
        {
            label: '退出', click: () => {
                mainWindow.webContents.send('setOffDevice');
                setTimeout(() => {
                    killDongle();
                    mainWindow.close()
                }, 100)
            }
        }
    ]);
    tray.setContextMenu(contextMenu);
    tray.on('click', () => {
        mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
    });
    tray.setToolTip('作业助手');
    ipcMain.on('resetDongle', () => {
        tray.setImage(unconnectdIco);

        killDongle();
        setTimeout(() => {
            ls = initDongle()
        }, 4000);
    });
    ipcMain.on('connectSuccess', () => {
        tray.setImage(connectdIco);
    });
    /** 注册快捷键 */
    globalShortcut.register('Control+E', () => {
        // console.log('CommandOrControl+ is pressed');
        mainWindow.webContents.openDevTools();
    });

    globalShortcut.register('Control+R', () => {
        // console.log('CommandOrControl+ is pressed');
        mainWindow.webContents.reload();
    });

    mainWindow.loadURL(winURL);
    mainWindow.on('close', killDongle);
    mainWindow.on('closed', () => {
        mainWindow = null;
    });

}

app.on('gpu-process-crashed', () => {
    app.relaunch();
    app.exit(0);
});


app.on('quit', () => {
    mainWindow.webContents.send('setOffDevice');
    killDongle();
});

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        mainWindow.webContents.send('setOffDevice');
        app.quit();
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow();
    }
});

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
